import HandleBtn from '@/components/HandleBar/btn';
import {
  ActionType,
  ModalForm,
  ProColumns,
  ProFormDatePicker,
  ProFormDependency,
  ProFormDigit,
  ProFormRadio,
  ProFormSelect,
  ProFormTimePicker,
  ProTable,
} from '@/components/Pro/';
import { getPvElectricityPriceType, getTimeType, getTOUPriceType } from '@/dictionary';
import {
  stationFeeControllerAddFee as add,
  stationFeeControllerBatch as batchHandle,
  stationFeeControllerDownloadExcel as downloadFile,
  stationFeeControllerEditFee as edit,
  stationFeeControllerList as getList,
} from '@/services/ess/stationFee';
import { downloadFetch } from '@/utils/downloadFile';
import { message, Modal, Space } from 'antd';
import React, { forwardRef, useImperativeHandle, useRef, useState } from 'react';
import { getIntl, useIntl } from 'umi';
import './../index.less';

const { confirm } = Modal;

/**
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.StationFeeDto) => {
  try {
    const res = await add({
      ...fields,
    });
    if (res?.success) {
      message.success(getIntl().formatMessage({ id: 'global.addSuccessfully' }));
      return true;
    }
    return false;
  } catch (error) {
    message.error(getIntl().formatMessage({ id: 'global.addFailedTips' }));
    return false;
  }
};

/**
 * @zh-CN 编辑节点
 * @param fields
 */
const handleEdit = async (fields: API.StationFeeDto) => {
  try {
    const res = await edit({
      ...fields,
    });
    if (res.success) {
      message.success(getIntl().formatMessage({ id: 'global.editedDuccessfully!' }));
      return true;
    }
    return false;
  } catch (error) {
    message.error(getIntl().formatMessage({ id: 'global.editFailedTips' }));
    return false;
  }
};

const PvPrice: React.FC<{
  stationId: number | string;
  eleType: number | string;
}> = ({ stationId, eleType }, ref) => {
  const intl = useIntl();
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.StationFeeDto>();
  const [selectedRowsState, setSelectedRows] = useState<API.StationFeeDto[]>([]);
  const [disabled, setDisabled] = useState(false);

  /**
   * @zh-CN 批量操作
   * @param type
   * @param selectedRows
   */
  function handleBatch(type: API.BatchOperatorReq.type, record = selectedRowsState) {
    if (record.length < 1) {
      message.warning(getIntl().formatMessage({ id: 'global.leastOne' }));
      return;
    }
    if (disabled) return;
    setDisabled(true);
    confirm({
      title: getIntl().formatMessage({ id: 'global.prompt' }),
      content: getIntl().formatMessage({ id: 'global.delTip' }),
      onOk: async () => {
        const res = await batchHandle({
          ids: record.map((row) => row.id),
          type,
        });
        if (res.success) {
          message.success(getIntl().formatMessage({ id: 'global.delSuccess' }));
          actionRef.current?.reloadAndRest?.();
        }
      },
      afterClose: () => {
        setDisabled(false);
      },
    });
  }

  useImperativeHandle(ref, () => ({
    handleBatch,
    add: () => {
      setCurrentRow(undefined);
      handleModalOpen(true);
    },
    selectedRowsState,
    download: () => {
      downloadFetch(downloadFile, {
        stationId: stationId,
        eleType: eleType,
      });
    },
  }));

  const columns: ProColumns<API.StationFeeDto>[] = [
    {
      title: intl.formatMessage({ id: 'systemManagement.generalProcedure.SN' }),
      hideInSearch: true,
      render: (dom, entity, index) => index + 1,
      width: 60,
    },
    {
      title: intl.formatMessage({ id: 'electricityPrice.year' }),
      dataIndex: 'year',
      hideInSearch: true,
      width: 80,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.siteAdministrationMenu.month' }),
      dataIndex: 'months',
      hideInSearch: true,
      width: 80,
    },
    {
      title: intl.formatMessage({ id: 'electricityPrice.electricityPriceClassification' }),
      dataIndex: 'elePriceType',
      valueEnum: getPvElectricityPriceType(),
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.siteAdministrationMenu.timeperiod' }),
      dataIndex: 'startTime',
      hideInSearch: true,
      render: (_, record) =>
        record?.timeType !== undefined && record?.timeType !== null
          ? `${record.startTime} - ${record.endTime}`
          : '-',
      width: 130,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.siteAdministrationMenu.Timeperiodtype' }),
      dataIndex: 'timeType',
      valueEnum: getTimeType(),
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'electricityPrice.electricityPrice' }),
      dataIndex: 'fee',
      hideInSearch: true,
      width: 130,
      render: (_, record) =>
        `${record.fee} ${intl.formatMessage({
          id: 'electricityPrice.priceUnit',
        })}`,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.generalProcedure.operation' }),
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space>
          <a
            key="edit"
            onClick={() => {
              handleModalOpen(true);
              setCurrentRow(record);
            }}
          >
            {intl.formatMessage({ id: 'systemManagement.generalProcedure.edit' })}
          </a>
          <a
            key="delete"
            className="global-del-color"
            onClick={() => handleBatch('DELETE', [record])}
          >
            {intl.formatMessage({ id: 'systemManagement.generalProcedure.delete' })}
          </a>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <ProTable<API.StationFeeDto, API.PageParams>
        headerTitle={false}
        actionRef={actionRef}
        rowKey="id"
        params={{
          stationId: stationId,
          eleType: eleType,
        }}
        request={getList}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
        search={false}
        PvPriceToolBarRender={false}
      />
      <ModalForm
        modalProps={{
          destroyOnClose: true,
        }}
        initialValues={{
          ...currentRow,
          elePriceCalculationType: currentRow?.elePriceCalculationType?.toString(),
          months: currentRow?.months?.split(','),
          timeType: currentRow?.timeType?.toString(),
          elePriceType: currentRow?.elePriceType?.toString(),
          voltageLevel: currentRow?.elePriceType?.toString(),
          rangeTime: currentRow ? [currentRow?.startTime, currentRow?.endTime] : undefined,
          year: currentRow?.year?.toString(),
        }}
        title={
          currentRow?.id
            ? intl.formatMessage({
                id: 'electricityPrice.editPhotovoltaicPowerGenerationElectricityPrice',
              })
            : intl.formatMessage({
                id: 'electricityPrice.addPhotovoltaicPowerGenerationElectricityPrice',
              })
        }
        width="730px"
        colProps={{ md: 12 }}
        open={createModalOpen}
        onOpenChange={handleModalOpen}
        onFinish={async (value) => {
          let success;
          value.stationId = stationId;
          value.months = value.months.join(',');
          value.startTime = value?.rangeTime?.[0] ?? '00:00:00';
          value.endTime = value?.rangeTime?.[1] ?? '23:59:59';
          value.eleType = Number(eleType);
          value.elePriceType = Number(value.elePriceType);

          delete value.rangeTime;
          if (currentRow?.id) {
            success = await handleEdit({ ...currentRow, ...value } as API.StationFeeDto);
          } else {
            success = await handleAdd(value as API.StationFeeDto);
          }
          if (success) {
            handleModalOpen(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormSelect
          label={intl.formatMessage({ id: 'electricityPrice.electricityPriceClassification' })}
          name="elePriceType"
          valueEnum={getPvElectricityPriceType()}
          initialValue={'1'}
          allowClear={false}
          rules={[
            {
              required: true,
              message: `${intl.formatMessage({
                id: 'electricityPrice.electricityPriceClassification',
              })}${intl.formatMessage({
                id: 'global.cannotBeEmpty',
              })}`,
            },
          ]}
        />
        <ProFormDependency name={['elePriceType']}>
          {({ elePriceType }) => {
            return (
              (elePriceType === '1' || elePriceType === '4') && (
                <ProFormRadio.Group
                  label={' '}
                  name="elePriceCalculationType"
                  valueEnum={getTOUPriceType()}
                  initialValue={'1'}
                />
              )
            );
          }}
        </ProFormDependency>
        <ProFormDatePicker.Year
          name="year"
          label={intl.formatMessage({ id: 'electricityPrice.year' })}
          rules={[
            {
              required: true,
              message: `${intl.formatMessage({
                id: 'electricityPrice.year',
              })}${intl.formatMessage({
                id: 'global.cannotBeEmpty',
              })}`,
            },
          ]}
          fieldProps={{
            style: {
              width: '100%',
            },
          }}
        />
        <ProFormDatePicker.Month
          name="months"
          label={intl.formatMessage({ id: 'systemManagement.siteAdministrationMenu.month' })}
          rules={[
            {
              required: true,
              message: intl.formatMessage({ id: 'systemManagement.requiredFields.month' }),
            },
          ]}
          fieldProps={{
            format: 'M',
            multiple: true,
            style: {
              width: '100%',
            },
            popupClassName: 'electricity-price-month-picker',
          }}
        />
        <ProFormDependency name={['elePriceType', 'elePriceCalculationType']}>
          {({ elePriceType, elePriceCalculationType }) => {
            let labelStr = '';
            if (elePriceType === '1') {
              labelStr = 'electricityPrice.electrovalence';
            } else if (elePriceType === '2') {
              labelStr = 'electricityPrice.feedInTariff';
            } else if (elePriceType === '3') {
              labelStr = 'electricityPrice.totalSubsidyPrice';
            } else if (elePriceType === '4') {
              labelStr = 'electricityPrice.offGridElectricityPrice';
            }
            return (
              <>
                {(elePriceType === '1' || elePriceType === '4') &&
                  elePriceCalculationType === '1' && (
                    <>
                      <ProFormTimePicker.RangePicker
                        name="rangeTime"
                        label={intl.formatMessage({
                          id: 'systemManagement.siteAdministrationMenu.timeperiod',
                        })}
                        rules={[
                          {
                            required: true,
                            message: `${intl.formatMessage({
                              id: 'systemManagement.siteAdministrationMenu.timeperiod',
                            })}${intl.formatMessage({
                              id: 'global.cannotBeEmpty',
                            })}`,
                          },
                        ]}
                      />
                      <ProFormSelect
                        label={intl.formatMessage({
                          id: 'systemManagement.siteAdministrationMenu.Timeperiodtype',
                        })}
                        name="timeType"
                        valueEnum={getTimeType()}
                        rules={[
                          {
                            required: true,
                            message: `${intl.formatMessage({
                              id: 'systemManagement.siteAdministrationMenu.Timeperiodtype',
                            })}${intl.formatMessage({
                              id: 'global.cannotBeEmpty',
                            })}`,
                          },
                        ]}
                      />
                    </>
                  )}
                {
                  <ProFormDigit
                    name="fee"
                    label={intl.formatMessage({
                      id: labelStr,
                    })}
                    fieldProps={{
                      addonAfter: intl.formatMessage({
                        id: 'electricityPrice.priceUnit',
                      }),
                      min: 0,
                      max: 1000000000,
                    }}
                    rules={[
                      {
                        required: true,
                        message: `${intl.formatMessage({
                          id: labelStr,
                        })}${intl.formatMessage({
                          id: 'global.cannotBeEmpty',
                        })}`,
                      },
                      () => ({
                        validator(_, value) {
                          if (value) {
                            return Promise.resolve();
                          }
                          return Promise.reject(
                            intl.formatMessage({
                              id: 'global.GreaterThanZero',
                            }),
                          );
                        },
                      }),
                    ]}
                  />
                }
              </>
            );
          }}
        </ProFormDependency>
      </ModalForm>
    </div>
  );
};

export type ToolBarProps = {
  tableRef: React.MutableRefObject<null>;
};
const PvPriceToolBarRender: React.FC<ToolBarProps> = ({ tableRef }) => {
  const intl = useIntl();

  return (
    <>
      <HandleBtn
        handleType="add"
        key="add"
        onClick={() => {
          tableRef?.current?.add();
        }}
      >
        {intl.formatMessage({ id: 'systemManagement.generalProcedure.new' })}
      </HandleBtn>
      <HandleBtn handleType="export" key="export" onClick={() => tableRef?.current?.download()}>
        {intl.formatMessage({ id: 'systemManagement.generalProcedure.export' })}
      </HandleBtn>
      <HandleBtn
        onClick={() => {
          tableRef?.current?.handleBatch('DELETE');
        }}
        handleType="delete"
        key="delete"
      >
        {intl.formatMessage({ id: 'systemManagement.generalProcedure.batchDelete' })}
      </HandleBtn>
    </>
  );
};

export default forwardRef(PvPrice);
export { PvPriceToolBarRender };
